package SystemC;

import java.util.LinkedHashMap;

import EventPackage.Event;
import EventPackage.EventManagerInterface;
import EventPackage.EventQueue;
import InstrumentationPackage.CommandConsoleOption;
import InstrumentationPackage.MessageWindow;
import TermioPackage.Termio;

public class SysCConsole {

	static LinkedHashMap<String, CommandConsoleOption> optionMap;
	private EventManagerInterface em = null;// Interface object to the event manager
	MessageWindow mw = null;
	
	private static void setOptions() {
		optionMap = new LinkedHashMap<String, CommandConsoleOption>();
		
		optionMap.put("1", new CommandConsoleOption("1","List all equipment installed\n",0,""));
		optionMap.put("Q", new CommandConsoleOption("Q","Stop System C\n",0,""));
	}
	
	public static void main(String args[])
	{
    	Termio UserInput = new Termio();	// Termio IO Object
		String EvtMgrIP;					// Event Manager IP address
		boolean Done = false;				// Main loop flag
		String Option;						// Menu choice from user
		MaintenanceMonitor Monitor = null;		// The environmental control system monitor
		
		/////////////////////////////////////////////////////////////////////////////////
		// Get the IP address of the event manager									   //
		/////////////////////////////////////////////////////////////////////////////////
		
		System.out.print("\n\nAttempting to register..." );

 		Monitor = new MaintenanceMonitor("MaintenanceMonitor", 700, 0, 198, 550, args, 91);
		
 		// Here we check to see if registration worked. If ef is null then the
 		// event manager interface was not properly created.

		if (Monitor.isRegistered())
		{
			setOptions();
			
			Monitor.start(); // Here we start the monitoring and control thread

			while (!Done)
			{
				// Here, the main thread continues and provides the main menu

				System.out.println( "\n\nSecurity Control System Command Console: \n" );

				System.out.println( "Select an Option: \n" );
				
				for (String key : optionMap.keySet()) {
					System.out.println(key + ":" + optionMap.get(key).getDescription());
				}
				
				System.out.println( "X: Stop Entire System\n" );
				System.out.print( "\n>>>> " );
				Option = UserInput.KeyboardReadString();

				//////////// option 1 ////////////

				
				if (Option.equalsIgnoreCase( "1" )) {
					Monitor.listEquipments();
				}
				
				//////////// option Q ////////////

				if (Option.equalsIgnoreCase( "Q" ))
				{
					// Here the user is done, so we set the Done flag and halt
					// the environmental control system. The monitor provides a method
					// to do this. Its important to have processes release their queues
					// with the event manager. If these queues are not released these
					// become dead queues and they collect events and will eventually
					// cause problems for the event manager.

					Monitor.Halt();
					Done = true;
					System.out.println( "\nConsole Stopped... Exit monitor mindow to return to command prompt." );
				} // if
				
				
				//////////// option X ////////////

				if (Option.equalsIgnoreCase( "X" ))
				{
					// Here the user is done, so we set the Done flag and halt
					// the environmental control system. The monitor provides a method
					// to do this. Its important to have processes release their queues
					// with the event manager. If these queues are not released these
					// become dead queues and they collect events and will eventually
					// cause problems for the event manager.

					Monitor.CompleteHalt();
					Done = true;
					System.out.println( "\nConsole Stopped... Exit monitor mindow to return to command prompt." );
				} // if

			} // while

		} else {

			System.out.println("\n\nUnable start the monitor.\n\n" );

		} // if
 		
	} // main
	
	public void run()
	{
		Event Evt = null;				// Event object
		EventQueue eq = null;			// Message Queue
		int EvtId = 0;					// User specified event ID
		int	Delay = 1000;				// The loop delay (1 second)
		boolean Done = false;			// Loop termination flag
		String listOfEquipment = null;  // The list of Active Equipments

		if (em != null)
		{

			mw = new MessageWindow("Maintenance Console", 0, 0);
			mw.WriteMessage( "Registered with the event manager." );

	    	try
	    	{
				mw.WriteMessage("   Participant id: " + em.GetMyId() );
				mw.WriteMessage("   Registration Time: " + em.GetRegistrationTime() );

			} // try

	    	catch (Exception e)
			{
				System.out.println("Error:: " + e);
 
			} // catch

			/********************************************************************
			** Here we start the main simulation loop
			*********************************************************************/

			while ( !Done )
			{
				// Here we get our event queue from the event manager
                            
                            System.out.println("\n\n>>>>>>>>>>>>> I AM RUNING I AM SYS CONSOLE THREAD");

				try
				{
					eq = em.GetEventQueue();

				} // try

				catch( Exception e )
				{
					mw.WriteMessage("Error getting event queue::" + e );

				} // catch

				// If there are messages in the queue, we read through them.
				// We are looking for EventIDs = 25, which has the list of equipments

				int qlen = eq.GetSize();

				for ( int i = 0; i < qlen; i++ )
				{
                                    System.out.println("\n\n>>>>>>>>>>>>> I HAVE NEW EVENTS: " + qlen);
					Evt = eq.GetEvent();

					if ( Evt.GetEventId() == 25 ) // List of Equipments
					{
						try
						{
							listOfEquipment = Evt.GetMessage();
							displayActiveEquipment(listOfEquipment);

						} // try

						catch( Exception e )
						{
							mw.WriteMessage("Error reading list of active equipments: " + e);

						} // catch

					} // if

					// If the event ID == 99 then this is a signal that the simulation
					// is to end. At this point, the loop termination flag is set to
					// true and this process unregisters from the event manager.

					if ( Evt.GetEventId() == 99 )
					{
						Done = true;

						try
						{
							em.UnRegister();

				    	} // try

				    	catch (Exception e)
				    	{
							mw.WriteMessage("Error unregistering: " + e);

				    	} // catch

				    	mw.WriteMessage( "\n\nSimulation Stopped. \n");

					} // if

				} // for

				// This delay slows down the sample rate to Delay milliseconds

				try
				{
					Thread.sleep( Delay );

				} // try

				catch( Exception e )
				{
					System.out.println( "Sleep error:: " + e );

				} // catch

			} // while

		} else {

			System.out.println("Unable to register with the event manager.\n\n" );

		} // if

	} // run
	
	
	/**
	 * Display the list of active equipments
	 * @param listOfEquipments string containing all active equipment
	 */
	private void displayActiveEquipment(String listOfEquipment) {
		
		System.out.println("List of active equipment:");
	
		// Split the string with equipment, which are divided by a semicolon (;).
		String[] list = listOfEquipment.split(";");
		for (int i = 0; i < list.length; i++) {
			System.out.println(list[i]);
		}
	}
	
} // SysCConsole
